//
//  AlbumFViewController.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "AlbumFViewController.h"
#import "ILButton.h"
#import "FAlbumList.h"
#import <UIImageView+WebCache.h>
#import <Accelerate/Accelerate.h>
#import "ILButton.h"
#import "FPlayViewController.h"
#import "UIImage+GaussianBlur.h"
#import "CoreDataManager.h"
#import "Album.h"
#import "WWPullDownButtonView.h"
#import "NSString+StringDate.h"
#import <MBProgressHUD.h>
#import "DownManger.h"
#import <MJRefresh.h>

#define UrlString @"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@"

@interface AlbumFViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UIScrollView *backScrollView;
@property(nonatomic, strong)UIImageView *backImageView;
@property(nonatomic, strong)UIImageView *albumImageView;
@property(nonatomic, strong)UIImageView *userImageView;
@property(nonatomic, strong)UILabel *userNameLabel;
@property(nonatomic, strong)UILabel *infoLabel;
@property(nonatomic, strong)UIImageView *assistImageView;
@property(nonatomic, strong)XHPathCover *pathCover;
@property(nonatomic, strong)UILabel *countLabel;
@property(nonatomic, strong)NSString *count;
@property(nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong)NSString *picUrl;
@property(nonatomic, strong)NSMutableArray *numberArray;
@property(nonatomic, strong)ILButton *collectionButton;
@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, strong)WWPullDownButtonView *pullView;
@property(nonatomic, strong)UIView *headerViewBack;
@property(nonatomic, strong)NSMutableArray *sectionArray;
@property(nonatomic, assign)NSInteger number;
@property(nonatomic, strong)NSString *toolNumber;
@end


@implementation AlbumFViewController

#pragma mark 加载图
-(MBProgressHUD *)progressView
{
    if (!_progressView) {
        _progressView = [[MBProgressHUD alloc]initWithView:self.view];
        _progressView.labelText = @"加载中";
        [_progressView setMode:MBProgressHUDModeIndeterminate];
        [_progressView show:YES];
        [_progressView NightWithType:UIViewColorTypeNormal];
    }
    return _progressView;
}

#pragma mark - 懒加载
#pragma mark 背景滚动视图
-(UIScrollView *)backScrollView
{
    if (!_backScrollView) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(180))];
    }
    return _backScrollView;
}

#pragma mark 辅助箭头视图
-(UIImageView *)assistImageView
{
    if (!_assistImageView) {
        _assistImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_infoLabel.frame.origin.x + _infoLabel.frame.size.width, _infoLabel.frame.origin.y, FitConstant_XorWidth(30), FitConstant_YorHeight(30))];
        _assistImageView.image = [UIImage imageNamed:@"xiangyou"];
    }
    return _assistImageView;
}

#pragma mark 详细信息
-(UILabel *)infoLabel
{
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(_userImageView.frame.origin.x, _userImageView.frame.origin.y + _userImageView.frame.size.height + FitConstant_YorHeight(5), self.view.frame.size.width - _userImageView.frame.origin.x - FitConstant_XorWidth(40), 30)];
        _infoLabel.font = [UIFont systemFontOfSize:12];
        _infoLabel.textColor = [UIColor whiteColor];
    }
    return _infoLabel;
}

#pragma mark 用户名
-(UILabel *)userNameLabel
{
    if (!_userNameLabel) {
        _userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(_userImageView.frame.origin.x + _userImageView.frame.size.width, _userImageView.frame.origin.y, FitConstant_XorWidth(200), FitConstant_YorHeight(40))];
        _userNameLabel.textColor = [UIColor whiteColor];
        _userImageView.image = [UIImage imageNamed:@"placeholderZh"];
    }
    return _userNameLabel;
}

#pragma mark 用户头像
-(UIImageView *)userImageView
{
    if (!_userImageView) {
        _userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_albumImageView.frame.origin.x + _albumImageView.frame.size.width + FitConstant_XorWidth(10), _albumImageView.frame.origin.y, FitConstant_XorWidth(40), FitConstant_XorWidth(40))];
        _userImageView.layer.cornerRadius = 20;
        _userImageView.layer.masksToBounds = YES;
        _userImageView.image = [UIImage imageNamed:@"placeholderZh"];
    }
    return _userImageView;
}

#pragma mark 专辑图
-(UIImageView *)albumImageView
{
    if (!_albumImageView) {
        _albumImageView = [[UIImageView alloc] initWithFrame:FitRectMake(20, 30, 80, 80)];
        _albumImageView.image = [UIImage imageNamed:@"placeholderZh"];
    }
    return _albumImageView;
}

#pragma mark tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - FitConstant_YorHeight(64)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = YES;
        [_tableView NightWithType:UIViewColorTypeNormal];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            _number++;
            [self didSelectionPullButton];
        }];
    }
    return _tableView;
}

#pragma mark 背景imageView
-(UIImageView *)backImageView
{
    if (!_backImageView) {
        _backImageView = [[UIImageView alloc] initWithFrame:_backScrollView.frame];
    }
    return _backImageView;
}

#pragma mark collectinButton
-(ILButton *)collectionButton
{
    if (!_collectionButton) {
        
        _collectionButton = [ILButton buttonWithType:UIButtonTypeCustom];
        _collectionButton.frame = CGRectMake(FitConstant_XorWidth(30), _backImageView.frame.size.height - FitConstant_YorHeight(40), FitConstant_XorWidth(140), FitConstant_YorHeight(40));
//        [_collectionButton addTarget:self action:@selector(collectionButtonAcion) forControlEvents:UIControlEventTouchUpInside];
        [self setCollectionTitle_Image];
        [_collectionButton addTarget:self action:@selector(coreDataAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _collectionButton;
}

-(void)setCollectionTitle_Image
{
    if ([_manager isExist:@"Album" SearchKey:@"albumId" SearchString:[NSString stringWithFormat:@"%@", _albumId]]) {
        _collectionButton.leftImageView.image = [UIImage imageNamed:@"shoucang"];
        _collectionButton.rightLabel.text = @"已收藏";
    }
    else{
        _collectionButton.leftImageView.image = [UIImage imageNamed:@"shoucang2"];
        _collectionButton.rightLabel.text = @"收藏";
    }
}

#pragma mark - 初始化界面

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [ThemeManage shareThemeManage].color3;
    self.tabBarController.tabBar.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view NightWithType:UIViewColorTypeNormal];
    self.title = _alumbTitel;
    
    [self initData];
    [self.view addSubview:self.progressView];
}

-(void)loadView
{
    [super loadView];
    _dataSource = [NSMutableArray array];
    _number = 1;
    _manager = [CoreDataManager shareManager];
    //添加图片滚动视图
    [self.view addSubview:self.tableView];
//    self.tableView.tableHeaderView = self.backScrollView;
    _pathCover = [[XHPathCover alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 180)];
//    [_pathCover setBackgroundImage:[UIImage imageNamed:@"placeholderCh_Larger"]];
    _pathCover.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = _pathCover;
    [_pathCover addSubview:self.backScrollView];
    [self.backScrollView addSubview:self.backImageView];
    self.backImageView.userInteractionEnabled = YES;
//    self.backImageView.backgroundColor = [UIColor grayColor];
    
    //添加背景图上的空间
    [self.backImageView addSubview:self.albumImageView];
    [self.backImageView addSubview:self.userImageView];
    [self.backImageView addSubview:self.userNameLabel];
    [self.backImageView addSubview:self.infoLabel];
    [self.backImageView addSubview:self.assistImageView];
    
    [self.backImageView addSubview:self.collectionButton];
    
//    ILButton *otherButton = [ILButton buttonWithType:UIButtonTypeCustom];
//    otherButton.frame = CGRectMake(FitConstant_XorWidth(200), _backImageView.frame.size.height - FitConstant_YorHeight(40), FitConstant_XorWidth(140), FitConstant_YorHeight(40));
//    [otherButton addTarget:self action:@selector(otherButtonAcion) forControlEvents:UIControlEventTouchUpInside];
//    otherButton.leftImageView.image = [UIImage imageNamed:@"f-yuwoxiangguan"];
//    otherButton.rightLabel.text = @"相关";
//    [self.backImageView addSubview:otherButton];
}

#pragma mark - 获取数据
-(void)initData
{
    if (self.track) {
        [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%ld/true/%ld/20?device=iPhone", self.track, _number] WithDataBlock:^(id data) {
            FAlbumDetail *detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"album"]];
            
            [self.userImageView sd_setImageWithURL:[NSURL URLWithString:detail.avatarPath]];
            [self.albumImageView sd_setImageWithURL:[NSURL URLWithString:detail.coverLarge] placeholderImage:[UIImage imageNamed:@"placeholderZh"]];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:detail.coverLarge]]];
            if (!image) {
                image = [UIImage imageNamed:@"placeholderZh"];
            }
            _pathCover.bannerImageView.image = [UIImage blurryImage:image withBlurLevel:0.2];
            self.infoLabel.text = detail.intro;
            if (detail.nickname) {
                self.userNameLabel.text = detail.nickname;
            }
            _count = [[data objectForKey:@"tracks"] objectForKey:@"totalCount"];
            _countLabel.text = [NSString stringWithFormat:@"%@", [[data objectForKey:@"tracks"] objectForKey:@"totalCount"]];
            _toolNumber = [NSString stringWithFormat:@"%@", [[data objectForKey:@"tracks"] objectForKey:@"totalCount"]];

            for (NSDictionary *each in [[data objectForKey:@"tracks"] objectForKey:@"list"]) {
                FAlbumList *list = [[FAlbumList alloc] init];
                [list setValuesForKeysWithDictionary:each];
                [self.dataSource addObject:list];
            }
            [self.tableView reloadData];
            
            _albumId = [NSString stringWithFormat:@"%@", [[data objectForKey:@"album"] objectForKey:@"albumId"]];
            _alumbTitel = [[data objectForKey:@"album"] objectForKey:@"title"];
            _picUrl = detail.coverLarge;
            [_progressView removeFromSuperview];
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }];
    }
     else {
        [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?device=iPhone&position=2&title=%@", _albumId, _number, _alumbTitel] WithDataBlock:^(id data) {
            
            FAlbumDetail *detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"album"]];
            
            [self.userImageView sd_setImageWithURL:[NSURL URLWithString:detail.avatarPath]];

            [self.albumImageView sd_setImageWithURL:[NSURL URLWithString:detail.coverLarge]  completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

            }];
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:detail.coverLarge]]];
            if (!image) {
                image = [UIImage imageNamed:@"placeholderZh"];
            }
            _pathCover.bannerImageView.image = [UIImage blurryImage:image withBlurLevel:0.2];
            self.infoLabel.text = detail.intro;
            if (detail.nickname) {
                self.userNameLabel.text = detail.nickname;
            }
            _count = [[data objectForKey:@"tracks"] objectForKey:@"totalCount"];
            _countLabel.text = [NSString stringWithFormat:@"%@", [[data objectForKey:@"tracks"] objectForKey:@"totalCount"]];
            _toolNumber = [NSString stringWithFormat:@"%@", [[data objectForKey:@"tracks"] objectForKey:@"totalCount"]];
            
            for (NSDictionary *each in [[data objectForKey:@"tracks"] objectForKey:@"list"]) {
                FAlbumList *list = [[FAlbumList alloc] init];
                [list setValuesForKeysWithDictionary:each];
                [self.dataSource addObject:list];
            }
            [self.tableView reloadData];
            _picUrl = detail.coverLarge;
            [_progressView removeFromSuperview];
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        }];
    }
}

#pragma coreDataAction
-(void)coreDataAction:(UIButton *)button
{
    if ([_manager isExist:@"Album" SearchKey:@"albumId" SearchString:[NSString stringWithFormat:@"%@", _albumId]]) {
        //取消收藏
        _collectionButton.leftImageView.image = [UIImage imageNamed:@"shoucang2"];
        _collectionButton.rightLabel.text = @"收藏";
        [_manager deleteAlbum:[NSString stringWithFormat:@"%@", _albumId]];
    }
    else{
        //收藏对象
        Album *play = [NSEntityDescription insertNewObjectForEntityForName:@"Album" inManagedObjectContext:_manager.managedObjectContext];
        
        //给属性赋值
        play.albumId = [NSString stringWithFormat:@"%@", _albumId];
        play.indexTitle = _alumbTitel;
        play.imagUrl = _picUrl;
        [_manager saveContext];
        [self.tableView reloadData];
        _collectionButton.leftImageView.image = [UIImage imageNamed:@"shoucang"];
        _collectionButton.rightLabel.text = @"已收藏";
    }
    
}

#pragma mark - 选集列表方法
-(void)didSelectionPullButton
{
//    [self.dataSource removeAllObjects];
    if (_dataSource.count == [_toolNumber integerValue]) {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    else{
        [self initData];
    }
    //NSLog(@"123");
}

#pragma mark - tableView代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifer = @"cell";
    FTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell) {
        cell = [[FTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    if (_dataSource.count != 0) {
        cell.types = FTableViewCellTypePlayList;
        cell.titleLabel.text = [_dataSource[indexPath.row] title];
        cell.timeLabel.font = [UIFont systemFontOfSize:15 + FitFont];
        cell.timeLabel.text = [NSString stringWithTimeString:[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@", [_dataSource[indexPath.row] albumDuration]]]];
        cell.countLabel.text = [NSString stringWithFormat:@"%@", [_dataSource[indexPath.row] playtimes]];
        //下载block
        cell.block = ^(){
            [[DownManger shareManger].dowmArray addObject:_dataSource[indexPath.row]];
        };
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    _headerViewBack = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
    _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
//    [_countLabel NightWithType:UIViewColorType3];
    [_countLabel NightWithType:UIViewColorTypeNormal];
    if (_count) {
        _countLabel.text = [NSString stringWithFormat:@"  共%@集", _count];
    }
    [_headerViewBack addSubview:_countLabel];
    
//    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    button1.frame = FitRectMake(285, 15, 18, 18);
//    [button1 setImage: [UIImage imageNamed:@"f-beijingyinle"] forState:UIControlStateNormal];
//    [button1 addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
//    [_headerViewBack addSubview:button1];
    
    if (_count) {
        NSInteger section = [_count integerValue] / 20 + 1;
        NSInteger number = [_count integerValue] % 20;
        _sectionArray = [NSMutableArray array];
        for (NSInteger i = 0; i < section - 1; i++) {
            [_sectionArray addObject:[NSString stringWithFormat:@"%ld-%ld", i * 20 + 1, i * 20 + 20]];
        }
        [_sectionArray addObject:[NSString stringWithFormat:@"%ld-%ld", (section - 1) * 20 + 1, (section - 1) * 20 + number]];
//        _pullView = [[WWPullDownButtonView alloc] initWithFrame:FitRectMake(305, 8, 40, 30) WithTitle:@"选集" WithInfoArray:_sectionArray WithSuperView:button1 WithHeight:FitConstant_YorHeight(667 - 15 - 18 - 15 - 18 - 18) WithSupTableView:self.tableView];
//        _pullView.delegate = self;
//        [self.tableView addSubview:_pullView];
    }
    
    return _headerViewBack;
}
#pragma mark button1的方法
-(void)buttonAction
{
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FPlayViewController *playerVC = [[FPlayViewController alloc] init];
    FAlbumList *list = _dataSource[indexPath.row];
    playerVC.albumId = [NSString stringWithFormat:@"%@", list.albumId];
    playerVC.trackID = [NSString stringWithFormat:@"%@", list.trackId];
    playerVC.trackUid = [NSString stringWithFormat:@"%@", list.uid];
    [PlayerButton shareButton].hidden = YES;
    [self.navigationController pushViewController:playerVC animated:YES];
}

#pragma mark- scroll delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [_pathCover scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_pathCover scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_pathCover scrollViewWillBeginDragging:scrollView];
}

@end
